package cn.yunhe.controller;

import cn.yunhe.entity.ChildType;
import cn.yunhe.entity.Product;
import cn.yunhe.service.ProductService;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

@WebServlet("/AddProductServlet")
public class AddProductServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SmartUpload su=new SmartUpload();
        JspFactory jspFactory=JspFactory.getDefaultFactory();
        PageContext pageContext=jspFactory.getPageContext(this,req,resp,null,true,8192,true);
        su.initialize(pageContext);
        su.setCharset("UTF-8");
        try {
            su.upload();
            su.save("images/product");
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        String pic=su.getFiles().getFile(0).getFileName();
        Request request=su.getRequest();
        String productName=request.getParameter("productName");
        int chtypeid=Integer.parseInt(request.getParameter("chtypeid"));
        ChildType childType=new ChildType();
        childType.setChtypeid(chtypeid);
        double price=Double.parseDouble(request.getParameter("price"));
        String brand=request.getParameter("brand");
        int store=Integer.parseInt(request.getParameter("store"));
        int barcode=Integer.parseInt(request.getParameter("barcode"));
        Product product=new Product(productName,price,pic,store,brand,barcode,childType);
        ProductService productService=new ProductService();
        boolean flag=productService.addProduct(product);
        if (flag){
            resp.sendRedirect("manage/manage-result.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
